//
//  LYQNewFeatureView.swift
//  SwiftWeibo
//
//  Created by 刘英群 on 2017/2/7.
//  Copyright © 2017年 刘英群. All rights reserved.
//

import UIKit

//新特性视图
class LYQNewFeatureView: UIView {
    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var startButton: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBAction func startStatus(_ sender: Any) {
        
    }

    class func newFeatureView() -> LYQNewFeatureView{
        
        let nib = UINib(nibName: "LYQNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! LYQNewFeatureView
        
        //从xib加载试图默认 600*600
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    override func awakeFromNib() {
        
        //使用自动布局设置的洁面，从xib加载默认是600*600大小
        // 添加四个图像视图
        let count = 4
        let rect = UIScreen.main.bounds
        
        for i in 0..<count {
            
            let imageName = "new_feature_\(i + 1)"
            let iv = UIImageView(image: UIImage(named: imageName))
            
            //设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(iv)
        }
        
        //指定scrollView的属性
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.delegate = self
        
        //隐藏按钮
        startButton.isHidden = true
    }
}

extension LYQNewFeatureView: UIScrollViewDelegate{
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        //1. 滚动到最后一屏，让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        //2. 判断是否最后一页
        if page == scrollView.subviews.count {
            
            print("欢迎欢迎， 热烈欢迎")
            removeFromSuperview()
        }
        
        //3. 如果是倒数第二页，显示按钮
        startButton.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //0 一旦滚动隐藏按钮
        startButton.isHidden = true
        
        // 1.计算当前的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        // 2.设置分页控件
        pageControl.currentPage = page
        
        // 3.分页控件的隐藏
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}
